﻿using Elsa.Models;
using Elsa.Services;
using Elsa.Services.Models;
using SqlSugar;
using Zhp.Workflow.Models;

namespace Zhp.Workflow
{
    public class WorkflowRefresher<T> : WorkflowContextRefresher<T> where T : class
    {
        private readonly ISqlSugarClient _dbContext;

        public WorkflowRefresher(ISqlSugarClient sqlSugarClient)
        {
            _dbContext = sqlSugarClient;
        }

        public override async ValueTask<T> LoadAsync(LoadWorkflowContext context, CancellationToken cancellationToken = default)
        {
            return await _dbContext.Queryable<T>().InSingleAsync(context.ContextId);
        }

        public override async ValueTask<string> SaveAsync(SaveWorkflowContext<T> context, CancellationToken cancellationToken = default)
        {
            var entity = await _dbContext.Queryable<T>().InSingleAsync(context.ContextId);
            if (entity != null)
            {
                entity = _dbContext.Utilities.TranslateCopy(context.Context);

                //流程表单审批状态和流程状态
                var obj = (IBaseWorkflow)entity;
                var input = context.WorkflowExecutionContext.Input as ApproveInput;
                if (input.Action == ApproveActionEnum.Submit || context.WorkflowExecutionContext.Status == WorkflowStatus.Finished)
                {
                    if (input.Action == ApproveActionEnum.Submit)
                    {
                        obj.Submit(context.WorkflowExecutionContext.WorkflowInstance.Id, context.WorkflowExecutionContext.WorkflowInstance.Name, input.UserId, input.UserName);
                    }
                    if (context.WorkflowExecutionContext.Status == WorkflowStatus.Finished)
                    {
                        if (input.Action == ApproveActionEnum.Agree)
                        {
                            obj.FinishAgree();
                        }
                        else if (input.Action == ApproveActionEnum.Refuse)
                        {
                            obj.FinishRefuse();
                        }
                        else
                        {
                            obj.Finish();
                        }
                    }
                }
                else
                {
                    obj.Approve();
                }
                await _dbContext.UpdateableByObject(obj).ExecuteCommandAsync();
            }

            return context.ContextId;
        }
    }

}
